<template>
  <div class="afterInvestDel-page" v-if="analysisType==1 || navActive==1">
    <pubChunk :mt="20">
      <span slot="title" class="flex-v-center">
        <span>历史走势图</span>
        <el-button-group v-if="navActive==2" style="margin-left: 22px;">
          <el-button
            :type="analysisType == 1 ? 'primary' : ''"
            size="small"
            @click="analysisTypeHandle(1)"
          >
            收益分析
          </el-button>
          <el-button
            :type="analysisType == 2 ? 'primary' : ''"
            size="small"
            @click="analysisTypeHandle(2)"
          >
            净值分析
          </el-button>
        </el-button-group>
      </span>
      <div slot="headLeft">
        <div class="flex wrap">
          <el-date-picker
            style="width: 280px; margin-left: 14px;"
            v-model="chart_date"
            type="daterange"
            align="right"
            unlink-panels
            size="small"
            @change="pickerChange"
            :clearable="false"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
          <el-button-group style="margin-left: 14px;">
            <el-button
              size="small"
              :type="dateFreq == 1 ? 'primary' : ''"
              :disabled="defaultDateFreq > 1"
              @click="dateFreq = 1"
            >
              日频
            </el-button>
            <el-button
              size="small"
              :type="dateFreq == 2 ? 'primary' : ''"
              :disabled="defaultDateFreq > 2"
              @click="dateFreq = 2"
            >
              周频
            </el-button>
            <el-button
              size="small"
              :type="dateFreq == 3 ? 'primary' : ''"
              @click="dateFreq = 3"
            >
              月频
            </el-button>
          </el-button-group>
          <el-checkbox
            style="margin-left: 14px;"
            class="flex-v-center"
            v-model="showBeyondIncome"
          >
            显示超额曲线
          </el-checkbox>
        </div>
      </div>
      <chart1Head
        ref="chart1Head"
        :more_chart1_nav_list2="more_chart1_nav_list2"
        :chartDate.sync="chart_date"
        :oldDate="oldDate"
        @sameSection="sameSectionHandle"
        @sameSectionReal="sameSectionRealHandle"
        :hasReal="Object.keys(realquery).length ? true : false"
      ></chart1Head>
      <Chart1
        v-if="
          compositionId &&
          indexTypes.length &&
          chart_date.length &&
          hasClassify &&
          strategy_dels.strategyName &&
          one_contrastOptions_list_parent.length
        "
        :titleDataType="titleDataType"
        @viewObj="viewObjHandle"
        @sectionChartDate="sectionChartDateHandle"
        @realContrastHnadle="$emit('realContrastHnadle')"
        :id="navActive==2?'investIntoSubInvest':'Chart1'"
        :userId="userId"
        :ids="compositionId"
        :lineEcahrts_showAll="lineEcahrts_showAll"
        :id_index="indexTypes"
        :defaultDateFreq.sync="defaultDateFreq"
        :dateFreq.sync="dateFreq"
        :chart_date="chart_date"
        :sameSection="sameSection"
        :sameSectionReal="sameSectionReal"
        :warehouseAdjustmentCycle="warehouseAdjustmentCycle"
        :showBeyondIncome="showBeyondIncome"
        :name1="strategy_dels.strategyName"
        :name2="strategy_dels.strategyName"
        :realquery="realquery"
        @beyondIncome2Change="(val) => $emit('beyondIncome2Change', val)"
        :indexNames="one_contrastOptions_list_parent"
        :typePage="navActive == 1 ? 'combManage' : 'combManage-strategy'"
        :height="280"
        width="100%"
      />
      <Chart
        v-if="
          strategy_dels.strategyName &&
          !hasClassify
        "
        :refreshKey="list_netWorthLine.length"
        :y-name="strategy_dels.strategyName"
        :legendStatus="legendStatus"
        :data="list_netWorthLine"
        :contrastIndex_obj="contrastIndex_obj"
        @legendStatus="legendStatusHandle"
        :defaultDateFreq.sync="defaultDateFreq"
        :indexs.sync="formData.types"
        :dateFreq.sync="dateFreq"
        @clearRealquery="clearRealqueryHandle"
        :realquery="realquery"
        :biIndex.sync="biIndex"
        :showBeyondIncome="showBeyondIncome"
        :indexNames="one_contrastOptions_list_parent"
        @viewObj="viewObjHandle"
        :height="280"
        width="100%"
        :contrastOptions_obj="contrastOptions_obj_parent"
      />

      <div
        class="flex-vh-center borDrag"
        v-else-if="list_netWorthLine == null && !hasClassify && hasClassify !== 'true'"
        style="height: 400px; margin-top: 24px;"
      >
        <img style="color: #666;" src="../../../../assets/nodata.png" alt="" />
        <div style="color: #888; font-size: 22px;">
          此区间无两个以上净值数据，无法绘制曲线
        </div>
      </div>
    </pubChunk>
  </div>
</template>
<script>
import { parseTime, deepClone } from '@/utils'
import pubChunk from '@/components/investComn/pubChunk.vue'
import Chart1 from '@/components/Charts/strategyComb/groupManage/chart1.vue'
import Chart from '@/components/Charts/lineEcharts_netWorthAnalysis2.vue'
import chart1Head from '@/components/investComn/chart1Head_v3.vue'
import { riskIndexCalc } from '@/utils/pro'
import mixin from './mixins'
import { getStrategyNetWorthLine, findIntersection } from '@/api/policyManage'
export default {
  mixins: [mixin],
  components: { pubChunk, Chart1, Chart, chart1Head },
  data() {
    return {
      _chart_date: [],
      chart_date: [],
      oldDate: [],
      more_chart1_nav_list2: [],

      legendStatus: {}, // 记录历史走势图图例状态
      contrastIndex_obj: {}, // 收益走势对比指数
      formData: {
        types: [],
      },
      biIndex: '', // 记录选取超额曲线

      realquery: {},
      strategy_dels: {},
      list_netWorthLine: [], //净值曲线
      showBeyondIncome: false, // 超额收益
      showReal: true, // 显示实盘
      defaultDateFreq: undefined, // 频率
      dateFreq: undefined, // 频率
      list_riskIndicators: [], // 收益风险指标
      nominalAmount: '',
      list_riskIndicators_key1: 1,
      list_riskIndicators_key2: 0,
      sameSection: false,
      compositionId: 0,
      sameSectionReal: false,
      chartDate_cb: [],
      lineEcahrts_showAll: false,
    }
  },
  props: {
    indexTypes: {
      type: Object | Array,
    },
    navActive: {
      type: String | Number,
    },
    titleDataType: {
      type: String | Number,
    },
    chart_date_parent: {
      type: Object | Array,
    },
    warehouseAdjustmentCycle: {
      type: String | Number,
      default: 1,
    },
    chart1List: {
      type: Object | Array,
    },
    contrastOptions_obj_parent: {
      type: Object | Array,
    },
    one_contrastOptions_list_parent: {
      type: Object | Array,
    },
    analysisType: {
      type: Number | String,
    },
  },
  watch: {
    'formData.types': {
      handler(newVal, oldVal) {
        console.log(newVal)
        this.list_netWorthLine = []
        this.$emit('beyondIncome2Change2', newVal)
        if(this.chart_date[0]) {
          this.getnetWorthLine(this.chart_date[0], this.chart_date[1])
        }
      },
      deep: true,
    },
    indexTypes: {
      handler(newVal, oldVal) {
        this.formData.types = newVal
      },
      deep: true,
    },
    chartDate_cb: {
      handler(dates) {
        // this.chart_date = deepClone(dates)
      },
      deep: true,
      immediate: true,
    },
    chart_date: {
      handler(date, oldDate) {
        if (oldDate.length !== 0 && date[0]) {
          this.list_netWorthLine = []
          this.getnetWorthLine(date[0], date[1])
          this.$emit('update:chart_date_parent', date)
        }
      },
    },
  },
  created() {},
  mounted() {},
  computed: {},
  methods: {
    chartInit(strategy_dels) {
      this.strategy_dels = strategy_dels
      this.compositionId = strategy_dels.riskIndicatorsBean.compositionId
      const start_date = parseTime(strategy_dels.makeTime, '{y}-{m}-{d}')
      const end_date = parseTime(strategy_dels.netWorthDetialBean.networthTime)
      this.chart_date = [start_date, end_date]
      this.oldDate = deepClone(this.chart_date)
      this._chart_date = [start_date, end_date]
      // 更多--年度
      let year0 = Number(this._chart_date[0].slice(0, 4))
      const year1 = Number(this._chart_date[1].slice(0, 4))
      this.more_chart1_nav_list2 = []
      while (year0 <= year1) {
        this.more_chart1_nav_list2.push(year0 + '年度')
        year0++
      }
      this.$emit('update:moreChart1NavList2', this.more_chart1_nav_list2)
    },
    analysisTypeHandle(val) {
      if(val==2) this.chart_date = JSON.parse(JSON.stringify(this.oldDate))
      this.$emit('update:analysisType', val)
    },
    pickerChange(date) {
      this.cns_active = null
      this.$emit('sameSection', false)
      this.$emit('update:chartDate', date)
    },
    clearRealqueryHandle(val) {
      this.realquery = val
      if(this.chart_date[0]) {
        this.getnetWorthLine(this.chart_date[0], this.chart_date[1])
      }
    },
    // 收益曲线
    getnetWorthLine(startDate, endDate) {
      if (this.sameSection) {
        this.findIntersection(startDate, endDate)
        return
      }
      getStrategyNetWorthLine({
        userId: this.userId,
        strategyId: this.strategyId,
        startDate,
        endDate,
        indexTypes: this.formData.types,
        realStrategySince: this.sameSectionReal,
        ...this.realquery,
      })
        .then((res) => {
          console.log('净值曲线', res)
          this.list_netWorthLine = res.body
        })
        .catch(() => {
          this.list_netWorthLine = null
        })
    },
    findIntersection(startTime, endTime) {
      findIntersection({
        userId: this.userId,
        strategyId: this.strategyId,
        startTime,
        endTime,
        indexTypes: this.formData.types,
        ...this.realquery,
      })
        .then((res) => {
          console.log('同区间净值曲线', res)
          this.list_netWorthLine = res.body
        })
        .catch(() => {
          this.list_netWorthLine = null
        })
    },
    viewObjHandle(data) {
      this.$emit('update:chart1List', riskIndexCalc(data))
    },
    riskRecursionHandle(resList, list) {
      list.map((items, i) => {
        const resList_i = resList.findIndex((item) => item.name == items.name)
        if (resList_i != -1) {
          const res = resList[resList_i]
          list[i] = {
            children: items.children,
            rowKey: items.rowKey,
            weight: items.weight,
            initMoney: items.initMoney,
            nominalAmount: items.nominalAmount,
            ...res,
          }
        } else if (items.children) {
          // 分类
          items.children.forEach((_) => {
            list[i] = {
              annualFluctuationsRate: '--',
              sharpeRate: '--',
              maxBackIncomDay: '--',
              maximumDrawdownRate: '--',
              calmarRate: '--',
              investWinningRate: '--',
              ...list[i],
            }
          })
        }
        if (items.children) this.riskRecursionHandle(resList, items.children)
      })
      // list[0].nominalAmount = this.nominalAmount
      return list
    },
    legendStatusHandle(obj) {
      this.legendStatus = obj
    },
    sameSectionHandle(val) {
      console.log('sameSectionHandle', !this.titleDataType);
      this.sameSection = val
      if(!this.titleDataType) this.findIntersection(this._chart_date[0], this._chart_date[1])
    },
    sectionChartDateHandle(chart_date) {
      this.chartDate_cb = chart_date
    },
    sameSectionRealHandle(val) {
      console.log('sameSectionRealHandle');
      this.sameSectionReal = val
    },
  },
}
</script>
<style lang="scss" scoped>
.afterInvestDel-page {
  padding: 0;
}
</style>
